<template>
    <div class="app-container">
        <el-form :model="queryParams"
                 ref="queryForm"
                 :inline="true"
                 v-show="showSearch"
                 label-width="68px">
            <el-form-item label="是否有效"
                          prop="isValid">
                <el-select v-model="queryParams.isValid"
                           placeholder="请选择"
                           clearable
                           size="small">
                    <el-option v-for="dict in isValidOptions"
                               :key="dict.dictValue"
                               :label="dict.dictLabel"
                               :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="是否为新注册" prop="isNewAccount">
        <el-select v-model="queryParams.isNewAccount" placeholder="请选择是否为新注册" clearable size="small">
          <el-option
            v-for="dict in isNewAccountOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->
            <el-form-item label="用户名"
                          prop="userName">
                <el-input v-model="queryParams.userName"
                          placeholder="请输入用户名"
                          clearable
                          size="small"
                          @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号"
                          prop="cellPhone">
                <el-input v-model="queryParams.cellPhone"
                          placeholder="请输入用户名"
                          clearable
                          size="small"
                          @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="注册日期"
                          prop="since">
                <el-date-picker clearable
                                size="small"
                                v-model="queryParams.since"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择账号的注册日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="同步日期"
                          prop="syncTime">
                <el-date-picker clearable
                                size="small"
                                v-model="queryParams.syncTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择账号的同步日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="当前等级"
                          prop="loyaltyTier">
                <el-select v-model="queryParams.loyaltyTier"
                           placeholder="请选择当前等级"
                           clearable
                           size="small">
                    <el-option v-for="dict in loyaltyTierOptions"
                               :key="dict.dictValue"
                               :label="dict.dictLabel"
                               :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="失效时间"
                          prop="failureTime">
                <el-date-picker clearable
                                size="small"
                                v-model="queryParams.failureTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择失效时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="cyan"
                           icon="el-icon-search"
                           size="mini"
                           @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh"
                           size="mini"
                           type="primary"
                           @click="resetQuery">重置</el-button>

                <el-button icon="el-icon-refresh"
                           size="mini"
                           type="danger"
                           @click="openToken=true">导入token</el-button>

                <el-button icon="el-icon-refresh"
                           size="mini"
                           type="danger"
                           @click="openDateDialog=true">同步</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading"
                  :data="accountList"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection"
                             width="55"
                             align="center" />
            <el-table-column label="用户名"
                             align="center"
                             width="155"
                             prop="userName" />
            <el-table-column label="手机号"
                             width="155"
                             align="center"
                             prop="cellPhone" />
            <el-table-column label="生日"
                             align="center"
                             prop="birthday"
                             width="120">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否有效"
                             align="center"
                             prop="isValid"
                             :formatter="isValidFormat" />
            <!-- <el-table-column label="是否为新注册" align="center" prop="isNewAccount" :formatter="isNewAccountFormat" /> -->
            <el-table-column label="账号名称"
                             align="center"
                             prop="firstName" />
            <el-table-column label="当前星星数"
                             align="center"
                             prop="loyaltyPoints" />
            <el-table-column label="注册日期"
                             align="center"
                             prop="since"
                             width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.since, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="当前等级"
                             align="center"
                             prop="loyaltyTier"
                             :formatter="loyaltyTierFormat" />
            <el-table-column label="升级星星数"
                             align="center"
                             prop="pointsToNextTier" />
            <el-table-column label="下一等级"
                             align="center"
                             prop="nextTierName"
                             :formatter="loyaltyTierFormat1" />
            <el-table-column label="同步时间"
                             align="center"
                             prop="syncTime"
                             width="180">
                <template slot-scope="scope">
                    <span>{{ formatDate(scope.row.syncTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="失效时间"
                             align="center"
                             prop="failureTime"
                             width="180">
                <template slot-scope="scope">
                    <span>{{ formatDate(scope.row.failureTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作"
                             align="center"
                             class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini"
                               type="text"
                               icon="el-icon-edit"
                               @click="handleUpdate(scope.row)"
                               v-hasPermi="['starbucks:account:edit']">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList" />
        <!-- 添加或修改星巴克账号对话框 -->
        <el-dialog title="导入token"
                   :visible.sync="openToken"
                   width="500px"
                   append-to-body>
            <el-form ref="elForm"
                     :model="formData"
                     :rules="rules"
                     size="medium"
                     label-width="100px">
                <el-form-item label="token"
                              prop="token">
                    <el-input v-model="formData.token"
                              type="textarea"
                              placeholder="请输入token"
                              :autosize="{minRows: 4, maxRows: undefined}"
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item size="large">
                    <el-button type="primary"
                               @click="submitForm">提交</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 同步 -->
        <el-dialog :visible.sync="openDateDialog"
                   title="选择同步时间"
                   append-to-body>
            <el-form ref="elForm"
                     :model="dateFormData"
                     :rules="rulesDate"
                     size="medium"
                     label-width="100px">
                <el-form-item label="日期范围"
                              prop="dates">
                    <el-date-picker type="datetimerange"
                                    v-model="dateFormData.dates"
                                    :style="{width: '100%'}"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    range-separator="至"
                                    clearable></el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary"
                           @click="handelConfirm">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listRewards } from '@/api/starbucks/rewards'
import { formatDate } from '@/utils/index'
import {
    listAccount,
    getAccount,
    delAccount,
    addAccount,
    updateAccount,
    exportAccount,
    updateInfo,
    insertByToken,
} from '@/api/starbucks/account'

export default {
    name: 'Account',
    data() {
        return {
            dateFormData: {
                dates: null,
            },
            rulesDate: {
                dates: [
                    {
                        required: true,
                        message: '日期范围不能为空',
                        trigger: 'change',
                    },
                ],
            },
            openDateDialog: false,
            formData: {
                token: '',
            },
            rules: {
                token: [
                    {
                        required: true,
                        message: '请输入token',
                        trigger: 'blur',
                    },
                ],
            },
            openToken: false,
            //优惠券列表
            rewardsList: null,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 星巴克账号表格数据
            accountList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 账号是否有效字典
            isValidOptions: [],
            // 是否为新注册字典
            isNewAccountOptions: [],
            // 当前等级字典
            loyaltyTierOptions: [],

            // 优惠券查询参数
            queryRewardsParams: {
                token: '',
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                token: null,
                userName: null,
                userId: null,
                cellPhone: null,
                birthday: null,
                deviceName: null,
                isValid: null,
                isNewAccount: null,
                firstName: null,
                lastName: null,
                gender: null,
                loyaltyPoints: null,
                since: null,
                loyaltyTier: null,
                pointsToNextTier: null,
                nextTierName: null,
                syncTime: null,
                failureTime: null,
            },
            // 表单参数
            form: {},
            statusOptions: null,
        }
    },
    created() {
        this.getList()
        this.getDicts('num_yes_no').then((response) => {
            this.isValidOptions = response.data
        })
        this.getDicts('num_yes_no').then((response) => {
            this.isNewAccountOptions = response.data
        })
        this.getDicts('starbucks_loyalty_tier').then((response) => {
            this.loyaltyTierOptions = response.data
        })
        this.getDicts('starbucks_rewards_status').then((response) => {
            this.statusOptions = response.data
        })
    },
    methods: {
        close() {
            this.openDateDialog = false
        },
        handelConfirm() {
            if (this.dateFormData.dates) {
                let query = {
                    endTime: this.formatDate(this.dateFormData.dates[1]),
                    startTime: this.formatDate(this.dateFormData.dates[0]),
                }
                updateInfo(query)
                    .then((res) => {
                        console.log(res)
                        if (res.code === 200) {
                            this.$message.success(res.msg)
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                    .catch((e) => {
                        console.log(e)
                    })
            }
        },
        formatDate,
        submitForm() {
            this.$refs['elForm'].validate((valid) => {
                if (!valid) return
                // TODO 提交表单
                insertByToken(encodeURIComponent(this.formData.token)).then((res) => {
                    if (res.code === 200) {
                        this.$message.success(res.msg)
                        this.$refs['elForm'].resetFields()
                        this.openToken = false
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            })
        },
        resetForm() {
            this.$refs['elForm'].resetFields()
        },
        // 状态字典翻译
        statusFormat(row, column) {
            return this.selectDictLabel(this.statusOptions, row.status)
        },
        getRewardsList() {
            listRewards(this.queryRewardsParams).then((response) => {
                this.rewardsList = response.rows
                this.open = true
            })
        },
        /** 查询星巴克账号列表 */
        getList() {
            this.loading = true
            listAccount(this.queryParams).then((response) => {
                this.accountList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 账号是否有效字典翻译
        isValidFormat(row, column) {
            return this.selectDictLabel(this.isValidOptions, row.isValid)
        },
        // 是否为新注册字典翻译
        isNewAccountFormat(row, column) {
            return this.selectDictLabel(
                this.isNewAccountOptions,
                row.isNewAccount
            )
        },
        // 当前等级字典翻译
        loyaltyTierFormat(row, column) {
            return this.selectDictLabel(
                this.loyaltyTierOptions,
                row.loyaltyTier
            )
        },
        loyaltyTierFormat1(row, column) {
            return this.selectDictLabel(
                this.loyaltyTierOptions,
                row.nextTierName
            )
        },
        // 取消按钮
        cancel() {
            this.open = false
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.open = true
            this.title = '添加星巴克账号'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.queryRewardsParams.token = row.token
            this.getRewardsList()
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$confirm(
                '是否确认删除星巴克账号编号为"' + ids + '"的数据项?',
                '警告',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(function () {
                    return delAccount(ids)
                })
                .then(() => {
                    this.getList()
                    this.msgSuccess('删除成功')
                })
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams
            this.$confirm('是否确认导出所有星巴克账号数据项?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(function () {
                    return exportAccount(queryParams)
                })
                .then((response) => {
                    this.download(response.msg)
                })
        },
    },
}
</script>
